package com.xul.yygh.user.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.xul.yygh.common.helper.JwtHelper;
import com.xul.yygh.common.result.Result;
import com.xul.yygh.user.service.UserInfoService;
import com.xul.yygh.user.utils.ConstantWxPropertiesUtil;
import com.xul.yygh.user.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import model.com.xul.yygh.model.user.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xul
 * @create 2021-07-15 9:54
 */

@Api(tags = "微信操作接口")
@Controller
@RequestMapping("api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation("微信扫描后调用回调函数")
    @GetMapping("callback")
    public String callback(String code) {
        // 1.获取到临时的票据
        System.out.println("code=" + code);
        // 2.拿着code和微信id 密钥 请求微信固定的地址 得到两个值
        // 使用code 和 appid 以及appscrect 换取到access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtil.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        // 3.使用httpclient请求这个地址
        String accessTokenInfo = null;
        try {
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo=" + accessTokenInfo);
            // 4.从返回的字符串中获取到 openid 和 access_token
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");
            // 5.根据openid判断数据库中有没有微信用户信息
            UserInfo userInfo = userInfoService.selectUserInfoByOpenid(openid);
            if (userInfo == null) {
                // 6.没有数据就拿着openid和access_token请求微信的地址 得到扫描人的信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultInfo=" + resultInfo);
                // 7.得到请求数据resultInfo后 取出扫描人信息 解析用户信息
                JSONObject ResultUserInfoJson = JSONObject.parseObject(resultInfo);
                String nickname = ResultUserInfoJson.getString("nickname");
                // 8.取出用户信息存入数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            // 9.返回name和token
            Map<String, String> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            // 10.判断数据库是否有用户手机号
            // 前端判断 如果openid不为空 绑定手机号 如果openid为空 不需要绑定手机号
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            // 11.页面将带数据 重定向到winxin/callback.vue里面
            return "redirect:" + ConstantWxPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token=" +
                    map.get("token") + "&openid=" + map.get("openid") + "&name=" +
                    URLEncoder.encode(map.get("name"), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取微信登录参数
     *
     * @return
     */
    @ApiOperation("获取微信登录参数")
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result getQrConnect() {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantWxPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            String wxOpenRedirectUrl = ConstantWxPropertiesUtil.WX_OPEN_REDIRECT_URL;
            wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
            map.put("redirectUri", wxOpenRedirectUrl);
            map.put("state", System.currentTimeMillis() + "");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
